@file:Suppress("unused")

package cn.qfys521

import cn.qfys521.SystemUtils.isLinux
import cn.qfys521.SystemUtils.isMacOs
import cn.qfys521.SystemUtils.isWindows
import cn.qfys521.SystemUtils.osName
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import org.openqa.selenium.Dimension
import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.OutputType
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions


class Html2Image {
    object Html2Image {
        private val driderPath =
            if (isWindows) Html2Image::class.java.getResource("/chromedriver_windows32.exe").path.substring(1)
            else if (isLinux) Html2Image::class.java.getResource("/chromedriver_linux_x64").path.substring(1)
            else if (isMacOs) Html2Image::class.java.getResource("/chromedriver_macos64").path.substring(1)
            else throw Exception("Unsupported System: $osName")

        private lateinit var options: ChromeOptions
        private lateinit var driver: ChromeDriver

        /**
         * 满窗口截图
         *
         * @param htmlPath html文件路径
         * @param imagePath 保存的图片位置(带名字)
         */
        fun screenshotWithMaximizeWindow(htmlPath:File , imagePath: File){
            System.setProperty("webdriver.gecko.driver", driderPath)
            options = ChromeOptions()
            options.addArguments("headless")
            driver = ChromeDriver(options)

            val width = (driver as JavascriptExecutor).executeScript("return document.documentElement.scrollWidth") as Long
            val height = (driver as JavascriptExecutor).executeScript("return document.documentElement.scrollHeight") as Long

            screenshot(htmlPath, imagePath , width.toInt() , height.toInt())
        }
        /**
         * 截图
         *
         * @param htmlPath html文件路径
         * @param imagePath 保存的图片位置(带名字)
         * @param width 宽
         * @param height 高
         */
        fun screenshot(htmlPath:File , imagePath: File , width : Int, height : Int){
            System.setProperty("webdriver.gecko.driver", driderPath)
            options = ChromeOptions()
            options.addArguments("headless")
            driver = ChromeDriver(options)
            try {
                driver.get(
                    if(htmlPath.startsWith("http://") or htmlPath.startsWith("https://")) "$htmlPath" else "file://${htmlPath.absolutePath}"
                )
                driver.manage().window().maximize()
                driver.manage().window().size = Dimension(width, height)

                val screenFile = driver.getScreenshotAs(OutputType.FILE)
                Files.copy(screenFile.toPath(), imagePath.toPath(), StandardCopyOption.REPLACE_EXISTING)

            }catch (e:Exception){
                throw Exception("Error while opening screenshot ${imagePath.absolutePath}", e)
            }finally {
                driver.close()
            }
        }

    }
}